package api

import (
	"context"
	"github.com/gin-gonic/gin"
	"log"
	book_rpc "month_zg5/book_srv/proto"
	"month_zg5/client/common/global"
	"month_zg5/client/userPost"
	"month_zg5/client/vender/aes"
	jwtRequest "month_zg5/client/vender/jwt"
	"net/http"
)

func UserLogin(ctx *gin.Context) {
	//username := ctx.PostForm("username")
	//password := ctx.PostForm("password")
	login := &userPost.UserLogin{}
	err := ctx.ShouldBindJSON(&login)
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		})
		return
	}
	res, err := global.BookClient.UserLogin(context.Background(), &book_rpc.UserLoginReq{Username: login.Username})
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		})
		return
	}

	//密码解密
	pass, err := aes.DePwdCode(res.Password)
	if string(pass) != login.Password {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  "密码错误",
		})
		return
	}
	//生成token
	token, err := jwtRequest.AuthToken(uint(res.Userid))
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "login success",
		"data": token,
	})
}
func Register(ctx *gin.Context) {
	login := userPost.UserRegister{}
	err := ctx.ShouldBindJSON(&login)
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		})
		return
	}
	log.Println(login, "///")
	//密码加密
	password, _ := aes.EnPwdCode([]byte(login.Password))
	res, err := global.BookClient.Register(context.Background(), &book_rpc.RegisterReq{
		Username: login.Username,
		Password: string(password),
		Email:    login.Email,
		Phone:    login.Phone,
	})
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "login success",
		"data": res.Userid,
	})
}
